package tnp.util;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class InitPath implements ServletContextListener {

	public static final String DEFAULT_WEB_APP_ROOT_KEY = "root";

	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent)
	 */
	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		// Do nothing.
	}

	/* (non-Javadoc)
	 * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent)
	 */
	@Override
	public void contextInitialized(ServletContextEvent sce) {
		ServletContext context = sce.getServletContext();
		String root = context.getRealPath("/");
		if (root == null) {
			throw new IllegalStateException(
			    "Cannot set web app root system property when WAR file is not expanded");
		}

		System.setProperty(DEFAULT_WEB_APP_ROOT_KEY, root);
		context.log("Set web app root system property: '" + DEFAULT_WEB_APP_ROOT_KEY + "' = [" + root + "]");
	}

}
